package com.jmu.edu.IMApplication.adapter;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.google.android.material.imageview.ShapeableImageView;
import com.jmu.edu.IMApplication.MyApplication;
import com.jmu.edu.IMApplication.R;
import com.jmu.edu.IMApplication.fragment.ImageDetailFragment;
import com.jmu.edu.IMApplication.utils.LoginUtils;
import com.jmu.edu.IMApplication.utils.ViewUtils;
import com.jmu.edu.IMApplication.utils.WillowUtils;

import java.io.File;
import java.util.List;

import cn.jpush.im.android.api.callback.DownloadCompletionCallback;
import cn.jpush.im.android.api.callback.GetAvatarBitmapCallback;
import cn.jpush.im.android.api.content.ImageContent;
import cn.jpush.im.android.api.content.TextContent;
import cn.jpush.im.android.api.enums.ContentType;
import cn.jpush.im.android.api.model.Conversation;
import cn.jpush.im.android.api.model.Message;
import cn.jpush.im.android.api.model.UserInfo;

public class ChatItemAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {


    private List<Message> messageList;
    private static final int LEFT_TYPE = 1;
    private static final int RIGHT_TYPE = 2;

    public void setMessageList(List<Message> messageList) {
        this.messageList = messageList;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        switch (viewType) {
            case LEFT_TYPE:
                return new LeftViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_chat_left, parent, false));
            case RIGHT_TYPE:
                return new RightViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_chat_right, parent, false));
            default:
                return new LeftViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_chat_left, parent, false));
        }

    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        Message message = messageList.get(position);
        if (holder instanceof LeftViewHolder) {
            handleMessage((LeftViewHolder) holder, message);

        } else if (holder instanceof RightViewHolder) {
            handleMessage((RightViewHolder) holder, message);
        }
    }


    @Override
    public int getItemViewType(int position) {
        UserInfo userInfo = messageList.get(position).getFromUser();
        if (userInfo.getUserID() == WillowUtils.getMyInfo().getUserID()) {
            return RIGHT_TYPE;
        } else {
            return LEFT_TYPE;
        }

    }

    @Override
    public int getItemCount() {
        Log.d("聊天界面适配器", "当前聊天记录数量:" + messageList.size());
        return messageList.size();
    }


    public static class LeftViewHolder extends RecyclerView.ViewHolder {

        private ShapeableImageView avatarImage, pictureImage;
        private TextView messageText;

        public LeftViewHolder(@NonNull View itemView) {
            super(itemView);
            avatarImage = itemView.findViewById(R.id.item_chat_left_avatar);
            messageText = itemView.findViewById(R.id.item_chat_left_message);
            pictureImage = itemView.findViewById(R.id.item_chat_left_picture);

        }
    }

    public static class RightViewHolder extends RecyclerView.ViewHolder {

        private ShapeableImageView avatarImage, pictureImage;
        private TextView messageText;

        public RightViewHolder(@NonNull View itemView) {
            super(itemView);
            avatarImage = itemView.findViewById(R.id.item_chat_right_avatar);
            messageText = itemView.findViewById(R.id.item_chat_right_message);
            pictureImage = itemView.findViewById(R.id.item_chat_right_picture);

        }
    }

    public void addItem(Message message) {
        messageList.add(message);
        notifyItemInserted(messageList.size() - 1);

    }

    private void handleMessage(LeftViewHolder holder, Message message) {
        UserInfo userInfo = message.getFromUser();
        userInfo.getAvatarBitmap(new GetAvatarBitmapCallback() {
            @Override
            public void gotResult(int i, String s, Bitmap bitmap) {
                if (bitmap != null) {
                    Glide.with(holder.avatarImage).load(bitmap).into(holder.avatarImage);
                }

            }
        });
        if (message.getContentType() == ContentType.image) {
            ImageContent imageContent = (ImageContent) message.getContent();

            // 获取原图地址，如果原图已经下载了就加载展示原图，否则展示缩略图
            String path = imageContent.getLocalPath();
            if (path == null) {
                // 获取缩略图地址
                String thumbnailPath = imageContent.getLocalThumbnailPath();
                // 如果地址为空说明缩略图还没有下载，那么此时下载缩略图
                if (thumbnailPath == null) {
                    imageContent.downloadThumbnailImage(message, new DownloadCompletionCallback() {
                        @Override
                        public void onComplete(int i, String s, File file) {
                            Glide.with(holder.pictureImage)
                                    .load(file)
                                    .into(holder.pictureImage);
                        }
                    });
                } else {
                    Glide.with(holder.pictureImage)
                            .load(thumbnailPath)
                            .into(holder.pictureImage);
                }
            } else {
                Glide.with(holder.pictureImage)
                        .load(path)
                        .into(holder.pictureImage);
            }


            //将图片设置为可见，将文本信息设置为不可见
            holder.pictureImage.setVisibility(View.VISIBLE);
            holder.messageText.setVisibility(View.GONE);
            holder.pictureImage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String tag = "imageDetail";
                    ImageDetailFragment show = (ImageDetailFragment) MyApplication.fragmentManager.findFragmentByTag(tag);
                    if (show == null) {
                        show = new ImageDetailFragment();
                    }
                    show.setImageMessage(message);
                    ViewUtils.showFragment(show, tag, R.anim.from_right, R.anim.out_right);
                }
            });

        } else if (message.getContentType() == ContentType.text) {
            TextContent textContent = (TextContent) message.getContent();
            holder.pictureImage.setVisibility(View.GONE);
            holder.messageText.setVisibility(View.VISIBLE);
            holder.messageText.setText(textContent.getText());
        }
    }

    private void handleMessage(RightViewHolder holder, Message message) {
        UserInfo userInfo = message.getFromUser();
        userInfo.getAvatarBitmap(new GetAvatarBitmapCallback() {
            @Override
            public void gotResult(int i, String s, Bitmap bitmap) {
                if (bitmap != null) {
                    Glide.with(holder.avatarImage).load(bitmap).into(holder.avatarImage);
                }

            }
        });
        if (message.getContentType() == ContentType.image) {
            ImageContent imageContent = (ImageContent) message.getContent();

            // 获取原图地址，如果原图已经下载了就加载展示原图，否则展示缩略图
            String path = imageContent.getLocalPath();
            if (path == null) {
                // 获取缩略图地址
                String thumbnailPath = imageContent.getLocalThumbnailPath();
                // 如果地址为空说明缩略图还没有下载，那么此时下载缩略图
                if (thumbnailPath == null) {
                    imageContent.downloadThumbnailImage(message, new DownloadCompletionCallback() {
                        @Override
                        public void onComplete(int i, String s, File file) {
                            Glide.with(holder.pictureImage)
                                    .load(file)
                                    .into(holder.pictureImage);
                        }
                    });
                } else {
                    Glide.with(holder.pictureImage)
                            .load(thumbnailPath)
                            .into(holder.pictureImage);
                }
            } else {
                Glide.with(holder.pictureImage)
                        .load(path)
                        .into(holder.pictureImage);
            }


            //将图片设置为可见，将文本信息设置为不可见
            holder.pictureImage.setVisibility(View.VISIBLE);
            holder.messageText.setVisibility(View.GONE);
            holder.pictureImage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String tag = "imageDetail";
                    ImageDetailFragment show = (ImageDetailFragment) MyApplication.fragmentManager.findFragmentByTag(tag);
                    if (show == null) {
                        show = new ImageDetailFragment();
                    }
                    show.setImageMessage(message);
                    ViewUtils.showFragment(show, tag, R.anim.from_right, R.anim.out_right);
                }
            });

        } else if (message.getContentType() == ContentType.text) {
            TextContent textContent = (TextContent) message.getContent();
            holder.pictureImage.setVisibility(View.GONE);
            holder.messageText.setVisibility(View.VISIBLE);
            holder.messageText.setText(textContent.getText());
        }
    }

}
